package com.lepu.app.fun.health.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.app.utils.AppWebChromClient;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserLocaljsObject;
import com.core.lib.utils.BrowserWebChromeClient;
import com.core.lib.utils.BrowserWebClient;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.CustomWebView;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.chat.util.ChatConst;
import com.lepu.app.fun.chat.util.ChatUtil;
import com.lepu.app.fun.index.activity.IndexFileActivity;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.main.activity.AppBroswerActivityBase;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;
import com.lepu.pasm.wxapi.WXPayEntryActivity;

import org.json.JSONObject;

import lib.share.model.Const;


public class HealthWebActivity extends AppBroswerActivityBase implements
        OnTopbarNewLeftLayoutListener, BrowserWebClient.BrowserWebClientDelegate,
        BrowserWebChromeClient.BrowserWebChromeDelegate, AsyncRequest, BrowserLocaljsObject.BrowserLocaljsObjectDelegate {

    public static final int TYPE_ORDER_PEI_ZHEN = 10;
    public static final int TYPE_ORDER_ZHUAN_ZHEN = 11;

    public static final int TYPE_PEI_ZHEN = 20;
    public static final int TYPE_ZHUAN_ZHEN = 21;

    public static final int TYPE_ORDER_PEI_ZHEN_INFO = 30;
    public static final int TYPE_ORDER_ZHUAN_ZHEN_INFO = 31;

    private static final String REQUEST_TEST = "request_test";

    private static final String GOTO_PEI_ZHEN_SUBMIT_ORDER = "goto::SubmitOrder?OrderID=";//随心诊跳转到去支付 陪诊 转诊 跳转我的订单
    private static final String GOTO_ZHUAN_ZHEN_PAY = "goto::weixin?orderNumber=";//随心诊跳转到去支付 陪诊 转诊 跳转我的订单

    private static final String GOTO_ZHUAN_ZHEN_HEALTH_FILE = "goto::MyReport";//跳转到检查报告 转诊
    private static final String GOTO_PEI_ZHEN_LOGIN = "goto::UserLogin";
    private static final String GOTO_ZHUAN_ZHEN_LOGIN = "goto::login";
    private static final String GOTO_LOGIN_RE = "goto::UserReLogin";


    private CustomWebView mWebView = null;
    private ProgressBar mProgressBar = null;
    private CustomTopBarNew mTopbar = null;

    private String mTopbarTitle = "";
    private int mType = 0;
    private String mOrderID = "";

    private String mCurrentLoadUrl = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.health_web_activity);

        init();
    }

    @Override
    public void onResume() {
        super.onResume();

        if(mType == TYPE_ZHUAN_ZHEN)
        {
            UmengHelper.onResume(this, UmengEvent.page_zhuanzhenfuwu);
        }else if(mType == TYPE_PEI_ZHEN)
        {
            UmengHelper.onResume(this, UmengEvent.page_peizhenfuwu);
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if(mType == TYPE_ZHUAN_ZHEN) {
            UmengHelper.onPause(this, UmengEvent.page_zhuanzhenfuwu);
        } else if(mType == TYPE_PEI_ZHEN)
        {
            UmengHelper.onPause(this, UmengEvent.page_peizhenfuwu);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    public void onBackPressed() {
        closePage();
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }

    private void closePage() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();

            //mTopbar.setTopbarTitle(mTopbarTitle);
            return;
        }

        //清理webview cookies
        Utils.clearCookies(this);

        finish(true);
    }

    /**
     * 初始化方法
     */
    @SuppressWarnings("unused")
	private void init() {
        // topbar
        mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
        mTopbar.setonTopbarNewLeftLayoutListener(this);
        mTopbar.setTopbarLeftLayout(R.drawable.app_icon_close, 0, 0);

        mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);
        mWebView = (CustomWebView) findViewById(R.id.webView);
        mWebView.setWebViewClient(new BrowserWebClient(this, this, mWebView));
        mWebView.setWebChromeClient(new AppWebChromClient(this, this, FILECHOOSER_RESULTCODE, REQUEST_SELECT_FILE));

        // test video
        BrowserLocaljsObject jsObj = new BrowserLocaljsObject(this);
        mWebView.addJavascriptInterface(jsObj, "local_obj");

        Bundle data = getIntent().getExtras();
        String url = "";
        if (data != null && data.size() > 0) {
            if (data.containsKey("url")) {
                mCurrentLoadUrl = data.getString("url");

                Utils.initWebViewSettings(mWebView, false);
            }

            if (data.containsKey("title")) {
                mTopbarTitle = data.getString("title");
            }

            if (data.containsKey("type")) {
                mType = data.getInt("type");
            }

            if (data.containsKey("OrderID")) {
                mOrderID = data.getString("OrderID");
            }
        }

        LinearLayout zhuanZhenMenuLayout = (LinearLayout) findViewById(R.id.zhuanZhenMenuLayout);
        if (mType == TYPE_ZHUAN_ZHEN || mType == TYPE_PEI_ZHEN) {
            zhuanZhenMenuLayout.setVisibility(View.VISIBLE);
            mTopbar.setTopbarTitle("");
        } else {
            zhuanZhenMenuLayout.setVisibility(View.GONE);
            mTopbar.setTopbarTitle(mTopbarTitle);
        }

        showWebViewUrl();
    }

    public void viewClick(View view) {
        int rid = view.getId();
        switch (rid) {
            case R.id.onlineChatButton:

                if(mType == TYPE_ZHUAN_ZHEN) {
                    UmengHelper.onPause(this, UmengEvent.event_fuwu_zhuanzhenkefu_lianxikefu);
                } else if(mType == TYPE_PEI_ZHEN)
                {
                    UmengHelper.onPause(this, UmengEvent.event_fuwu_peizhenfuwu_lianxikefu);
                }
                jumpOnlineChat();
                break;
            case R.id.serviceInfoButton:

                jumpServiceInfo();
                break;
            default:
                break;
        }
    }

    public void reloadLogin()
    {
        if (mType == TYPE_ORDER_PEI_ZHEN ||
                mType == TYPE_PEI_ZHEN ||
                mType == TYPE_ORDER_PEI_ZHEN_INFO) {

          mCurrentLoadUrl = Setting.getSuiXinZhenMainUrl();

        }else if (mType == TYPE_ORDER_ZHUAN_ZHEN ||
                mType == TYPE_ZHUAN_ZHEN ||
                mType == TYPE_ORDER_ZHUAN_ZHEN_INFO) {

            mCurrentLoadUrl = Setting.getZhuanZhenMainUrl();
        }
        showWebViewUrl();
    }

    private void showWebViewUrl() {

        if (!StringUtilBase.stringIsEmpty(mCurrentLoadUrl)) {
            if (mCurrentLoadUrl.startsWith(Setting.getSuiXinZhenMainUrl()) ||
                    mCurrentLoadUrl.startsWith(Setting.getZhuanZhenMainUrl())) {
                JSONObject params = new JSONObject();
                try {
                    params.put("DeviceID", Setting.DEVICEID);
                    params.put("ApplicationID", Setting.APPLICATIONID);

                    if (LoginUtil.checkIsLogin()) {
                        params.put("UserID", LoginUtil.getUserId());
                    } else {
                        params.put("UserID", "");
                    }

                    params.put("LoginToken", LoginUtil.getLoginToken());

                    if (mType == TYPE_PEI_ZHEN) {
                        //陪诊
                        params.put("URL", "ServiceList");
                    } else if (mType == TYPE_ORDER_PEI_ZHEN) {
                        //陪诊订单
                        params.put("URL", "OrderList");
                    } else if (mType == TYPE_ORDER_PEI_ZHEN_INFO) {
                        //陪诊订单详情
                        params.put("URL", "OrderDetail");
                        params.put("OrderID", mOrderID);
                    }
                    //===========================================================
                    else if (mType == TYPE_ZHUAN_ZHEN) {
                        //转诊
                        params.put("BranchID", Setting.getBranchID(HealthWebActivity.this));
                        params.put("URL", "Hospital");
                    } else if (mType == TYPE_ORDER_ZHUAN_ZHEN) {
                        //转诊订单
                        params.put("BranchID", Setting.getBranchID(HealthWebActivity.this));
                        params.put("URL", "Order");
                    }else if(mType == TYPE_ORDER_ZHUAN_ZHEN_INFO){
                        //转诊订单详情
                        params.put("BranchID", Setting.getBranchID(HealthWebActivity.this));
                        params.put("URL", "OrderDetail");
                        params.put("OrderID", mOrderID);
                    }

                } catch (Exception e) {
                }

                //byte[] datas = EncodingUtils.getBytes(map.toString(), "BASE64");
                byte[] datas = params.toString().getBytes();
                mWebView.postUrl(mCurrentLoadUrl, datas);
            } else {
                mWebView.loadUrl(mCurrentLoadUrl);
            }
        }
    }

    public void onProgressChanged(WebView view, int newProgress) {
        mProgressBar.setMax(100);
        if (newProgress < 100) {
            if (mProgressBar.getVisibility() == View.GONE) {
                mProgressBar.setVisibility(View.VISIBLE);
            }
            mProgressBar.setProgress(newProgress);
        } else {
            mProgressBar.setProgress(100);

            Animation animation = AnimationUtils.loadAnimation(this,
                    R.anim.lib_broswer_progress);
            // 运行动画
            mProgressBar.startAnimation(animation);
            // 将 spinner 的可见性设置为不可见状态
            mProgressBar.setVisibility(View.GONE);
        }
    }

    public void onPageStarted(String url) {
        LogUtilBase.LogD(null, "onPageStarted===>>" + url);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        LogUtilBase.LogD(null, "shouldOverrideUrlLoading == >>" + url);

        if(url.startsWith(GOTO_LOGIN_RE)){
            MainTabActivity.getInstance().mHandler.
                    sendEmptyMessage(MainTabActivity.MSG_SHOW_LOGIN_TOKEN_DIALOG);
        }
        else if (url.startsWith(GOTO_PEI_ZHEN_LOGIN) ||
                url.startsWith(GOTO_ZHUAN_ZHEN_LOGIN)) {
            gotoLogin();
        } else if (url.startsWith(GOTO_ZHUAN_ZHEN_HEALTH_FILE)) {
            gotoHealthFile();
        } else if (url.startsWith(GOTO_PEI_ZHEN_SUBMIT_ORDER)) {
            String OrderID = url.substring(GOTO_PEI_ZHEN_SUBMIT_ORDER.length());
            gotoOrderPay(OrderID,TYPE_ORDER_PEI_ZHEN);
        }else if (url.startsWith(GOTO_ZHUAN_ZHEN_PAY)) {
            String OrderID = url.substring(GOTO_ZHUAN_ZHEN_PAY.length());
            gotoOrderPay(OrderID,TYPE_ORDER_ZHUAN_ZHEN);
        }  else {
            mCurrentLoadUrl = url;
            showWebViewUrl();
        }
        return true;
    }

    public void onPageFinished(String url) {
        LogUtilBase.LogD(null, "onPageFinished===>>" + url);
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_TEST)) {
            LogUtilBase.LogD(null, "test success");
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        if (object.equals(REQUEST_TEST)) {
            LogUtilBase.LogD(null, "test fail");
        }
    }

    //===================================================================================================

    /**
     * 查看订单
     */
    private void gotoOrderInfoPage(String OrderID) {

        if (mType == TYPE_ORDER_PEI_ZHEN ||
                mType == TYPE_PEI_ZHEN ||
                mType == TYPE_ORDER_PEI_ZHEN_INFO) {

            Intent intent = new Intent(this, HealthWebActivity.class);
            intent.putExtra("OrderID", OrderID);
            intent.putExtra("url", Setting.getSuiXinZhenMainUrl());
            intent.putExtra("title", getString(R.string.health_title_pei_zhen_order_info));
            intent.putExtra("type", HealthWebActivity.TYPE_ORDER_PEI_ZHEN_INFO);
            startActivity(intent, true);

        }else if (mType == TYPE_ORDER_ZHUAN_ZHEN ||
                mType == TYPE_ZHUAN_ZHEN ||
                mType == TYPE_ORDER_ZHUAN_ZHEN_INFO) {

            Intent intent = new Intent(this, HealthWebActivity.class);
            intent.putExtra("OrderID", OrderID);
            intent.putExtra("url", Setting.getZhuanZhenMainUrl());
            intent.putExtra("title", getString(R.string.health_title_zhuan_zhen_order_info));
            intent.putExtra("type", HealthWebActivity.TYPE_ORDER_ZHUAN_ZHEN_INFO);
            startActivity(intent, true);

        }
    }

    public void jumpOrderSuccessDialog(final String OrderID) {
        jumpOrderPeiZhenSuccessDialog(OrderID);
    }

    public void jumpOrderFailDialog(final String message) {
        jumpOrderPeiZhenFailDialog(message);
    }

    /**
     * 陪诊订单支付成功
     */
    private void jumpOrderPeiZhenSuccessDialog(final String OrderID) {
        String message = "成功支付！";
        MyDialog dialog = new MyDialog(this)
                .setMessage(message)
                .setNegativeButton(R.string.health_order_go_health_file,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                finish(true);
                                gotoHealthFile();
                            }
                        })
                .setPositiveButton(R.string.health_order_go_health_order,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                finish(true);
                                gotoOrderInfoPage(OrderID);
                            }
                        });

        dialog.create(null);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.showMyDialog();
    }

    /**
     * 陪诊订单支付失败，或取消支付
     */
    private void jumpOrderPeiZhenFailDialog(String message) {
        MyDialog dialog = new MyDialog(this)
                .setMessage(message)
                .setNegativeButtonSplitImageHide(true)
                .setPositiveButton(R.string.app_ok,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                finish(true);
                            }
                        });

        dialog.create(null);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.showMyDialog();
    }

    /**
     * 健康档案中 检查报告
     */
    private void gotoHealthFile() {
        Intent intent = new Intent(HealthWebActivity.this, IndexFileActivity.class);
        intent.putExtra("index", 1);
        startActivity(intent, true);
    }

    /**
     * 去登录
     */
    private void gotoLogin() {
        LoginUtil.jumpLogin(this);
    }

    /**
     * 在线咨询
     */
    private void jumpOnlineChat() {
        // 聊天界面
        if (!LoginUtil.jumpLogin(this)) {
            ChatUtil.jumpChat(this, null, ChatConst.TYPE_ONLINE_CHAT_ONLINE);
        }
    }

    /**
     * 服务介绍
     */
    private void jumpServiceInfo() {

        String url = "";
        if(mType == TYPE_PEI_ZHEN)
        {
            url = Setting.getPeiZhenServiceInfoUrl();
        }else if(mType == TYPE_ZHUAN_ZHEN)
        {
            url = Setting.getZhuanZhenServiceInfoUrl();
        }

        Intent intent = new Intent(this, AppBroswerActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", "服务介绍");
        startActivity(intent, true);
    }

    /**
     * 去支付
     */
    private void gotoOrderPay(String orderId,int type) {

        boolean isInstallWx = AppManager.checkIfInstallApplication(this, Const.WX_PACKAGE_NAME);
        if (isInstallWx) {
            Intent intent = new Intent(this, WXPayEntryActivity.class);
            intent.putExtra("order_id", orderId);
            intent.putExtra("type", type);
            startActivity(intent, true);
        }else{
            UIHelper.showToast(this,"请先安装微信");
        }

    }

    // ================test==========================
    @Override
    public void getTitle(String title) {
        LogUtilBase.LogD(null, String.format("webview title====>>%s", title));

        if (TextUtils.isEmpty(mTopbarTitle)) {
            mTopbar.setTopbarTitle(title);
        }
    }

    @Override
    public void getVideoSrc(String videoSrc) {
        LogUtilBase.LogD(null,
                String.format("webview videoSrc===>>%s", videoSrc));
    }

    @Override
    public void getHtmlLength(int HtmlLength) {
        LogUtilBase.LogD(null,
                String.format("webview HtmlLength===>>%d", HtmlLength));
    }

    @Override
    public void getReferrer(String Referrer) {
        LogUtilBase.LogD(null,
                String.format("webview Referrer===>>%s", Referrer));
    }

    //=============================================
    @Override
    public void getArticleID(String arg0) {

    }

    @Override
    public void getCover(String arg0) {

    }

    @Override
    public void getDescription(String arg0) {

    }


}
